package cn.imvc.app.controllers;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.imvc.app.domains.Constants;
import cn.imvc.app.entities.Domain;
import cn.imvc.app.entities.Member;
import cn.imvc.app.models.DomainModel;
import cn.imvc.app.models.MemberModel;
import cn.imvc.core.Render;

@Controller
@RequestMapping("domain")
public class DomainControllerImpl implements DomainController {

	@Autowired
	MemberModel memberModel;
	
	@Autowired
	DomainModel domainModel;
	
	@RequestMapping("/domain.html")
	public String domain(Model model, String token) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			Domain domain = domainModel.findBymemberId(member.getId());
			if(domain != null){
				model.addAttribute("domain", Constants.DOMAIN_PREFIX + domain.getDomain() + Constants.DOMAIN_SUFFIX);
			}
			model.addAttribute("prefix", Constants.DOMAIN_PREFIX);
			model.addAttribute("suffix", Constants.DOMAIN_SUFFIX);
			return "domain/domain";
		} else {
			return "redirect:/member/login.html";
		}
	}
	
	@RequestMapping("/edit.html")
	@ResponseBody
	public String edit(Model model, String token, String newdomain) {
		Member member = memberModel.getLoginMember(token);
		Map<String, String> map = domainModel.updateDomain(member, newdomain);
		return Render.json(map);
	}
}
